;
(function() {
    new Vue({
        el: '#customer',
        data: {
            permissions: window.localStorage.getItem('permissions'),
            subNav: [
                { name: '全部', num: 0, type: '#', state: '#' },
                { name: '潜在客户', num: 0, type: 'PO', state: 'N' },
                { name: '意向客户', num: 0, type: 'YX', state: 'N' },
                { name: '成交客户', num: 0, type: 'CJ', state: 'N' },
                { name: '流失客户', num: 0, type: 'LS', state: 'N' },
                { name: '黑名单客户', num: 0, type: '#', state: 'Y' }
            ],
            subnavAct: '全部',
            limitArr: [10, 15, 20],
            params: {
                limit: 10,
                crrent: 1,
                keywork: null,
                subType: '#',
                subState: '#'
            },
            crList: [],
            policysList: [],
            rperson: {
                ids: [],
                name: null,
                list: []
            }, // 对接人
            customerParams: {
                type: [{ name: '公司', code: 'QY' }, { name: '个人', code: 'PE' }],
                typeAct: 'QY',
                state: [{ name: '是', code: 'Y' }, { name: '否', code: 'N' }],
                stateAct: 'N',
                channel: [
                    { name: '自行上门', code: 'SM' },
                    { name: '中介', code: 'ZJ' },
                    { name: '老客户推荐', code: 'TJ' },
                    { name: '互联网平台', code: 'NT' },
                    { name: '内部推荐', code: 'NJ' },
                    { name: '其他', code: 'ET' },
                ],
                channelAct: null,
                pylcType: [
                    { name: '潜在客户', code: 'PO' },
                    { name: '意向客户', code: 'YX' },
                    { name: '流失客户', code: 'LS' },
                    { name: '成交客户', code: 'CJ' }
                ],
                pylcTypeAct: null,
                industry: [],
                industryAct: null
            },
            customerFlag: false,
            addParams: {
                idcode: null,
                email: null,
                name: null,
                rperson: null,
                phone: null,
                qdName: null,
                memo: null
            },
            crTotal: 0,
            sortFlag: '#',
            sortCurmter: '#',
            typeArcms: {
                radio: [],
                check: [],
                input: [],
                text: []
            },
            beginTime:'',
            endTime:'',
        },
        filters: {
            formatDate: function(time) {
                if (time == undefined) return '--';
                return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
            },
            customerType: function(type) {
                return hlCodeConvert.customerType(type)
            },
            customerChannelType: function(type) {
                return hlCodeConvert.customerChannelType(type)
            },
            customerState: function(type) {
                return hlCodeConvert.customerState(type)
            }
        },
        computed: {},
        methods: {
            //获取自定义字段
            checkRadio: function(i, val) {
                var flag = false,
                    index0 = null;
                this.typeArcms.check[i].act.map(function(item, index) {
                    if (val == item) {
                        flag = true;
                        index0 = index;
                    }
                })
                if (flag) {
                    this.typeArcms.check[i].act.splice(index0, 1)
                    return
                }
                this.typeArcms.check[i].act.push(val)
            },
            getlistZdy: function() {
                var self = this;
                self.typeArcms = { radio: [], check: [], input: [], text: [] }
                hlhttp.get({
                    url: 'customer/field_config',
                    success: function(res) {
                        res.map(function(item) {
                            if (item.configType == 'C') {
                                if (item.fieldType == 'radio') {
                                    item.act = item.fieldRange.split(',')[0]
                                    self.typeArcms.radio.push(item)
                                }
                                if (item.fieldType == 'checkbox') {
                                    item.act = []
                                    self.typeArcms.check.push(item)
                                }
                                if (item.fieldType == 'tel' || item.fieldType == 'email') {
                                    item.act = ''
                                    self.typeArcms.input.push(item)
                                }
                                if (item.fieldType == 'text') {
                                    item.act = ''
                                    self.typeArcms.text.push(item)
                                }
                            }
                        })
                    }
                })
            },
            //升序
            upSort: function() {
                this.sortCurmter = 'RT'
                if (this.sortFlag == 'ASC') {
                    this.sortFlag = 'DESC'
                    $('.bt-icon').removeClass('icon-Gm-sort-ascending').addClass('icon-Gm-sort-descending')
                } else {
                    this.sortFlag = 'ASC'
                    $('.bt-icon').removeClass('icon-Gm-sort-descending icon-Gm-sort-default').addClass('icon-Gm-sort-ascending')
                }
                this.getCrList()
            },
            //获取所属行业
            getIndustry: function() {
                var _this = this;
                hlhttp.get({
                    url: 'configure/industry/dict',
                    success: function(res) {
                        _this.customerParams.industry = res
                    }
                })
            },
            //获取租户的数据访问策略
            policys: function() {
                var _this = this;
                hlhttp.get({
                    url: 'data_policys',
                    success: function(res) {
                        _this.policysList = res;
                    }
                })
            },
            //输入对接人进行搜索
            onInputDJR: function(e) {
                if (!this.rperson.name) {
                    if (!e.data) return;
                    this.rperson.name = e.data;
                }
                this.getDataGroup()
            },
            //判断有没有ids
            ifrpersonIds: function() {
                if (!this.rperson.ids.length) {
                    this.rperson.name = null
                }
            },
            //设置对接人name，获取id
            setRperson: function(name, id) {
                this.rperson.ids = [];
                this.rperson.name = name;
                this.rperson.ids.push(id)
                this.rperson.list = [];
            },
            //搜索负责人工作组组员列表
            getDataGroup: function() {
                var _this = this;
                _this.rperson.ids = [];
                hlhttp.get({
                    url: 'data_group/users/_search',
                    data: {
                        keyword: _this.rperson.name || '#'
                    },
                    success: function(res) {
                        _this.rperson.list = res;
                        for (var i = 0; i < _this.rperson.list.length; i++) {
                            if (_this.rperson.name.match(res[i])) {
                                _this.rperson.ids.push(res[i].userId)
                            }
                        }
                    }
                })
            },
            //列表切换
            subnavTab: function(name, type, state) {
                this.subnavAct = name;
                this.params.subType = type;
                this.params.subState = state;
                this.getCrList()
            },
            //重置111
            resetButton: function() {
                this.beginTime = ''
                this.endTime = ''
                this.params = { limit: 10, crrent: 1, keywork: null, subType: '#', subState: '#' };
                this.rperson = { ids: [], name: null, list: [] };
                this.subnavAct = '全部';
                this.getCrList()
            },
            //数量设置
            setLimit: function(num) {
                this.params.limit = num;
                this.getCrList()
            },
            //查看
            seeInfo: function(id) {
                window.localStorage.setItem('followUpFlag', 'false')
            },
            //跟进
            followInfo: function(id) {
                window.localStorage.setItem('followUpFlag', 'true')
            },
            //联系电话验证
            blurPhone: function() {
                if (this.addParams.phone) {
                    if (!checkTel(this.addParams.phone)) {
                        this.addParams.phone = null;
                        hl.toast('请填写正确的联系电话')
                    }
                }
            },
            getCrList1() {
                this.params.crrent = 1;
                this.getCrList()
            },
            //获取列表
            getCrList: function() {
                var _this = this;
                var data = {
                    begin_date: this.beginTime || '#', //付款开始日期
                    end_date: this.endTime || '#', //付款结束日期
                    key_word: _this.params.keywork ? _this.params.keywork.trim() : '#',
                    customer_state: _this.params.subType, //客户状态
                    black_state: _this.params.subState, //Y黑名单客户，N不是黑名单
                    page: _this.params.crrent, //请求页 Int
                    page_size: _this.params.limit, //每页数量 Int
                    rperson_ids: _this.rperson.ids.toString() || '#',
                    columns: this.sortCurmter, //，RT跟进时间
                    orders: _this.sortFlag //，ASC升序、DESC降序
                };

                hlhttp.get({
                    url: 'customers/_search',
                    data: data,
                    success: function(res) {
                        _this.subNav[0].num = res.pOCount + res.yXCount + res.cJCount + res.lSCount + res.bLCount;
                        _this.subNav[1].num = res.pOCount;
                        _this.subNav[2].num = res.yXCount;
                        _this.subNav[3].num = res.cJCount;
                        _this.subNav[4].num = res.lSCount;
                        _this.subNav[5].num = res.bLCount;
                        _this.crList = res;

                        window.localStorage.removeItem('contractNav')
                        $("#page").initPage(res.totalPage, _this.params.crrent, function(n) {
                            if (_this.params.crrent == n) return;
                            _this.params.crrent = n
                            _this.getCrList()
                        });
                        loginPrem.loginList()
                    }
                })

            },
            //客户类型
            customerType: function(code) {
                if (code === this.customerParams.typeAct) return false;
                if (code !== this.customerParams.typeAct) {
                    this.customerParams.typeAct = code
                }
            },
            //客户黑名单
            customerState: function(code) {
                this.customerParams.stateAct = code
            },
            //设置所属行业
            setIndustry: function(code) {
                this.customerParams.industryAct = code
            },
            //设置获取渠道
            setChannel: function(code) {
                this.customerParams.channelAct = code
            },
            //设置状态
            setpylcType: function(code) {
                this.customerParams.pylcTypeAct = code
            },
            // 线索详情转化而来的客户
            customerFromBusiness: function() {
                var data = window.sessionStorage.getItem('RENT_BUSINESS_CUSTOMER') ? JSON.parse(window.sessionStorage.getItem('RENT_BUSINESS_CUSTOMER')) : null
                if (data == null) return;
                this.customerFlag = true;
                this.customerParams.typeAct = data.customerType;
                this.addParams.name = data.customerName;
                this.customerParams.industryAct = data.industryCode;
                this.addParams.idcode = data.idcode;
                this.addParams.email = data.email;
                this.addParams.rperson = data.lperson;
                this.addParams.phone = data.phone;
            },
            validate: function() {
                if (!this.addParams.name) {
                    hl.toast('请填写客户名称')
                    return false;
                }
                if (!this.customerParams.industryAct) {
                    hl.toast('请选择所属行业')
                    return false;
                }
                if (this.addParams.email) {
                    if (!hlValidateUtil.validateEmail(this.addParams.email)) {
                        hl.toast('邮箱格式不符合')
                        return false;
                    }
                }
                if (!this.customerParams.channelAct) {
                    hl.toast('请选择获取渠道')
                    return false;
                }
                if (!this.customerParams.pylcTypeAct) {
                    hl.toast('请选择状态')
                    return false;
                }

                var flagCheck = false,
                    CheckName = [],
                    custom_fields = [],
                    flagInput = false,
                    InputName = [],
                    flagText = false,
                    textName = [],
                    flagText1 = false,
                    textName1 = [];
                this.typeArcms.radio.map(function(item) {
                    if (item.isValid == 'true') {
                        custom_fields.push({ config_code: item.configCode, config_value: item.act })
                    }
                })
                this.typeArcms.check.map(function(item) {
                    if (item.isValid == 'true') {
                        if (item.isRequired == 'true') {
                            if (!item.act.length) {
                                flagCheck = true;
                                CheckName.push(item.displayName);
                            }
                        }
                        custom_fields.push({ config_code: item.configCode, config_value: item.act.toString() || '#' })
                    }
                })
                this.typeArcms.input.map(function(item) {
                    if (item.isValid == 'true') {
                        if (item.isRequired == 'true') {
                            if (!item.act.replace(/^\s+|\s+$/g, '').length) {
                                flagInput = true;
                                InputName.push(item.displayName);
                            }
                        }
                        custom_fields.push({ config_code: item.configCode, config_value: item.act || '#' })
                    }
                })
                this.typeArcms.text.map(function(item) {
                    if (item.isValid == 'true') {
                        if (item.isRequired == 'true') {
                            if (!item.act.replace(/^\s+|\s+$/g, '').length) {
                                flagText = true;
                                textName.push(item.displayName);
                            }
                            if (item.act.replace(/^\s+|\s+$/g, '').length > item.fieldRange) {
                                flagText1 = true;
                                textName1.push(item.displayName + '的字数不能超过' + item.fieldRange + '个');
                            }
                        }
                        custom_fields.push({ config_code: item.configCode, config_value: item.act || '#' })
                    }
                })

                if (flagCheck) {
                    hl.toast('请选择' + CheckName[0])
                    return false;
                }
                if (flagInput) {
                    hl.toast('请填写' + InputName[0])
                    return false;
                }
                if (flagText) {
                    hl.toast('请填写' + textName[0])
                    return false;
                }
                if (flagText1) {
                    hl.toast(textName1[0])
                    return false;
                }

                return true;
            },
            //新建客户
            newAddCustomer: function() {
                if (!this.validate()) return false;

                var flagCheck = false,
                    CheckName = [],
                    custom_fields = [],
                    flagInput = false,
                    InputName = [],
                    flagText = false,
                    textName = [],
                    flagText1 = false,
                    textName1 = [];
                this.typeArcms.radio.map(function(item) {
                    if (item.isValid == 'true') {
                        custom_fields.push({ config_code: item.configCode, config_value: item.act })
                    }
                })
                this.typeArcms.check.map(function(item) {
                    if (item.isValid == 'true') {
                        if (item.isRequired == 'true') {
                            if (!item.act.length) {
                                flagCheck = true;
                                CheckName.push(item.displayName);
                            }
                        }
                        custom_fields.push({ config_code: item.configCode, config_value: item.act.toString() || '#' })
                    }
                })
                this.typeArcms.input.map(function(item) {
                    if (item.isValid == 'true') {
                        if (item.isRequired == 'true') {
                            if (!item.act.replace(/^\s+|\s+$/g, '').length) {
                                flagInput = true;
                                InputName.push(item.displayName);
                            }
                        }
                        custom_fields.push({ config_code: item.configCode, config_value: item.act || '#' })
                    }
                })
                this.typeArcms.text.map(function(item) {
                    if (item.isValid == 'true') {
                        if (item.isRequired == 'true') {
                            if (!item.act.replace(/^\s+|\s+$/g, '').length) {
                                flagText = true;
                                textName.push(item.displayName);
                            }
                            if (item.act.replace(/^\s+|\s+$/g, '').length > item.fieldRange) {
                                flagText1 = true;
                                textName1.push(item.displayName + '的字数不能超过' + item.fieldRange + '个');
                            }
                        }
                        custom_fields.push({ config_code: item.configCode, config_value: item.act || '#' })
                    }
                })

                var data = {
                    type: this.customerParams.typeAct, //客户类型，QY企业类型、PE个人类型
                    name: this.addParams.name, //客户名称
                    industry: this.customerParams.industryAct, //所属行业
                    lperson: this.addParams.rperson || '#', //联系人
                    phone: this.addParams.phone || '#', //联系电话
                    channel_type: this.customerParams.channelAct,
                    channel_name: this.addParams.qdName || '#', //渠道名称
                    customer_state: this.customerParams.pylcTypeAct,
                    memo: this.addParams.memo || '#', //备注
                    black_state: this.customerParams.stateAct,
                    idcode: this.addParams.idcode || '#',
                    email: this.addParams.email || '#',
                    customer_fields: JSON.stringify(custom_fields)
                }

                var self = this;
                var isFromBusinessDetails = hlUrlUtil.GetQueryString('isFromBusinessDetails')
                    // 如果为线索模块跳转而来新建客户  需调用线索模块接口
                if (isFromBusinessDetails) businessSendCreateRequest()
                if (!isFromBusinessDetails) sendCreateRequset()

                function sendCreateRequset() {
                    hlhttp.post({
                        url: 'customer',
                        data: data,
                        success: function() {
                            hl.toast('新建成功')
                            self.getCrList()
                            self.backButton()
                        }
                    })
                }

                function businessSendCreateRequest() {
                    data['sj_id'] = hlUrlUtil.GetQueryString('businessId');
                    hlhttp.put({
                        url: 'customer/biz_oppt_to_customer',
                        data: data,
                        success: function() {
                            hl.toast('新建成功')
                            self.getCrList()
                            self.backButton()
                        }
                    })
                }

            },
            //重置新建
            backButton: function() {
                this.addParams = { name: null, rperson: null, phone: null, qdName: null, memo: null }
                this.customerFlag = false;
                this.customerParams.typeAct = 'QY';
                this.customerParams.industryAct = null;
                this.customerParams.channelAct = null;
                this.customerParams.pylcTypeAct = null;
                this.customerParams.stateAct = 'N';
                this.typeArcms = { radio: [], check: [], input: [], text: [] }
                this.getlistZdy()
            }
        },
        created: function() {
            // 如果页面由线索详情转为客户跳转而来，则打开新增客户弹窗
            if (hlUrlUtil.GetQueryString('isFromBusinessDetails') == 'Y') this.customerFromBusiness();
        },
        mounted: function() {
            if (hlUrlUtil.GetQueryString('customerState')) {
                this.params.subType = hlUrlUtil.GetQueryString('customerState')
                this.subnavAct = '意向客户';
                this.params.subState = 'N'
            }
            this.getCrList()
            this.policys()
            this.getIndustry()
            this.getlistZdy()
            hlSelectUi()

            var _this = this;
            document.body.onclick = function() {
                _this.rperson.list = [];
            }
        }
    })

    function checkTel(tel) {
        // var mobile = /^1[3|4|5|7|8]\d{9}$/ , phone = /^0\d{2,3}-?\d{7,8}$/;
        // return mobile.test(tel) || phone.test(tel);
        var test = /^[\d\+\-\(\)]{10,20}$/i;
        return test.test(tel)
    }



}())